<template>
  <div class="add-author">
    <h2>添加作者</h2>
    <el-form :model="authorForm" :rules="rules" ref="authorFormRef" @submit.native.prevent="handleSubmit">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="authorForm.name" placeholder="请输入作者姓名"></el-input>
      </el-form-item>
      <el-form-item label="简介" prop="introduction">
        <el-input type="textarea" v-model="authorForm.introduction" placeholder="请输入作者简介"></el-input>
      </el-form-item>
      <el-form-item label="图片链接" prop="picture">
        <el-input v-model="authorForm.picture" placeholder="请输入图片链接"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      authorForm: {
        name: '',
        introduction: '',
        picture: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入作者姓名', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '请输入作者简介', trigger: 'blur' }
        ],
        picture: [
          { required: true, message: '请输入图片链接', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    handleSubmit() {
      this.$refs.authorFormRef.validate((valid) => {
        if (valid) {
          this.$http.post('/authors', this.authorForm)
            .then(response => {
              if (response.data) {
                this.$message.success('作者添加成功');
                // 跳转到 AuthorList 页面
                this.$router.push({ name: 'AuthorsList' });
              } else {
                this.$message.error('添加失败，请重试');
              }
            })
            .catch(error => {
              this.$message.error('添加失败，请稍后重试');
              console.error('添加作者请求出错:', error);
            });
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.add-author {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>